﻿using EasyDDD.AdminModule.Domain.AggregateSysMenu;
using EasyDDD.Domain;
using EasyDDD.Infrastructure;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EasyDDD.AdminModule.Domain
{
    /// 作废
    public class SysMenuDomainService: IDomainSevice
    {
        IRepository<SysMenu, SysMenuId> repository;
        //TODO: 考虑用Records查询
        IQueryable<SysMenu> query;

        public SysMenuDomainService(IRepository<SysMenu, SysMenuId> repository)
        {
            this.repository = repository;
            this.query = repository.AsQueryable();
        }

        //public bool CheckIsExist(SysMenuId id)
        //{
        //    return !query.Any(e => e.Id.Value == id.Value);
        //}

        //TODO: 实体验证三种方案
        //1.现在这样验证放到领域服务里 这样会多出个领域服务并且依赖了仓储
        //2.把验证抽象出来 领域服务依赖该抽象 实现放哪里还需要想想
        //3.验证放到CommandValidator验证里去 
        public void CheckIsPass(SysMenu entity)
        {
            if (query.Any(e => e.Id != entity.Id && e.Title == entity.Title))
            {
                throw new BusinessException("Title不能重复");
            }
            if (query.Any(e => e.Id != entity.Id && e.Name == entity.Name))
            {
                throw new BusinessException("Name不能重复");
            }
            if (query.Any(e => e.Id != entity.Id && e.Path == entity.Path))
            {
                throw new BusinessException("Path不能重复");
            }
            if (entity.ParentId != Guid.Empty && !query.Any(e => e.Id == new SysMenuId(entity.ParentId)))
            {
                throw new BusinessException("父菜单不存在");
            }
        }

        //public bool CheckTitlePass(string title)
        //{
        //    return query.Any(e => e.Title != title);
        //}

        public Task<SysMenu> Create(SysMenu entity)
        {
            CheckIsPass(entity);
            return repository.AddAsync(entity);
        }

        public Task<SysMenu> Update(SysMenu entity)
        {
            CheckIsPass(entity);
            return repository.UpdateAsync(entity);
        }

        public async Task<SysMenu> Delete(SysMenuId id)
        {
            var entity = await repository.GetAsync(id);
            if (entity == null)
            {
                throw new BusinessException("该条数据不存在或已被删除");
            }
            entity.Delete();
            return entity;
        }
    }
}
